package utils

import (
	"fmt"
	"log"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"os"
	"path"
	"strings"
)

type DownHeader struct {
	ImgUrl    string         //目标地址
	Cookie    *cookiejar.Jar //cookie
	Origin    string         // 来源地址
	UserAgent string
	SavePath  string
	SaveName  string
}

func NewDown(ImgIrl, Origin, UserAgent string, Cookie *cookiejar.Jar, SavePath string, SaveName string) *DownHeader {
	return &DownHeader{
		ImgUrl:    ImgIrl,
		Cookie:    Cookie,
		Origin:    Origin,
		UserAgent: UserAgent,
		SavePath:  SavePath,
		SaveName:  SaveName,
	}
}

func (down *DownHeader) DownImage() (savePath string) {
	savePath = down.SavePath + down.SaveName
	pwd, err := os.Getwd()
	if err != nil {
		panic("获取当前目录失败:" + err.Error())
	}
	dirFileName := path.Join(pwd, savePath)

	_, err = os.Stat(dirFileName)
	if err != nil {
		if !os.IsNotExist(err) {
			return
		}
	}

	client := &http.Client{
		Jar: down.Cookie,
	}

	req, err := http.NewRequest("GET", down.ImgUrl, nil)
	if err != nil {
		panic("Error creating request:" + err.Error())
	}

	req.Header.Set("User-Agent", down.UserAgent)
	req.Header.Set("referer", down.Origin)

	resp, err := client.Do(req)
	if err != nil {
		panic("Error making request:" + err.Error())
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return
	}

	err = SaveFile(savePath, resp.Body)
	if err != nil {
		panic("Error saving image:" + err.Error())
	}

	return
}

func down() {
	jar, err := cookiejar.New(nil)
	if err != nil {
		panic("Error creating cookie jar:" + err.Error())
	}
	down := NewDown("https://img.dxsbb.com/upFiles/infoImg/school/1670.jpg", "http://www.dxsbb.com", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36", jar, "", "1.jpg")
	resPath := down.DownImage()
	fmt.Printf(resPath)
}

// 报考大学
func DownloadImage(imgUrl, savePath, fileName string) {
	url, err := url.Parse(imgUrl)
	if err != nil {
		log.Fatalln("解析url错误", err)
	}
	strs := strings.Split(url.Path, ".")
	fileName = fileName + "." + strs[len(strs)-1]
	jar, err := cookiejar.New(nil)
	if err != nil {
		panic("创建cookie错误:" + err.Error())
	}

	initCookie := []*http.Cookie{
		{
			Name:   "HMACCOUNT",
			Value:  "5AB1E0DD977F5F53",
			Domain: ".gaokao.com",
			Path:   "/",
		},
		{
			Name:   "Hm_lpvt_17c8dee9c87e3ab669ce5dd4f88140ec",
			Value:  "1734612360",
			Domain: ".gaokao.cn",
			Path:   "/",
		},
		{
			Name:   "Hm_lvt_17c8dee9c87e3ab669ce5dd4f88140ec",
			Value:  "1734182179,1734612337",
			Domain: ".gaokao.cn",
			Path:   "/",
		},
		{
			Name:   "sajssdk_2015_cross_new_user",
			Value:  "1",
			Domain: ".gaokao.cn",
			Path:   "/",
		},
		{
			Name:   "BMAP_SECKEY",
			Value:  "6aFM2YArv0o6h6TJDNCmtHJhvtlx9DcMpBYJqIMix8aXn7Bos6tKGNt-PFjINcYcSGNi0151X3Ada6ysQbOGpDpm2euKTkxEoXqqACecg_hiM7kKSw3c9FCoN8BERWCcqBt-pcrPfrMLNgZn2nKN7XTok_89snJB9LPTmHKaKSoOgQVCT-cQB53c9fqhSM-o",
			Domain: ".gaokao.com",
			Path:   "/",
		},
	}

	jar.SetCookies(url, initCookie)
	downImg := NewDown(
		imgUrl,
		url.Host,
		"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
		jar,
		savePath,
		fileName)
	imgPath := downImg.DownImage()
	fmt.Println(imgPath)
}

func Example() {

	imgUrl := "https://college.gaokao.com/style/college/images/icon/1.png"
	url, err := url.Parse(imgUrl)
	strs := strings.Split(url.Path, "/")
	if err != nil {
		panic("解析url错误" + err.Error())
	}

	jar, err := cookiejar.New(nil)
	if err != nil {
		panic("创建cookie错误:" + err.Error())
	}

	initCookie := []*http.Cookie{
		{
			Name:   "HMACCOUNT",
			Value:  "5AB1E0DD977F5F53",
			Domain: ".gaokao.com",
			Path:   "/",
		},
		{
			Name:   "Hm_lpvt_17c8dee9c87e3ab669ce5dd4f88140ec",
			Value:  "1734612360",
			Domain: ".gaokao.cn",
			Path:   "/",
		},
		{
			Name:   "Hm_lvt_17c8dee9c87e3ab669ce5dd4f88140ec",
			Value:  "1734182179,1734612337",
			Domain: ".gaokao.cn",
			Path:   "/",
		},
		{
			Name:   "sajssdk_2015_cross_new_user",
			Value:  "1",
			Domain: ".gaokao.cn",
			Path:   "/",
		},
		{
			Name:   "BMAP_SECKEY",
			Value:  "6aFM2YArv0o6h6TJDNCmtHJhvtlx9DcMpBYJqIMix8aXn7Bos6tKGNt-PFjINcYcSGNi0151X3Ada6ysQbOGpDpm2euKTkxEoXqqACecg_hiM7kKSw3c9FCoN8BERWCcqBt-pcrPfrMLNgZn2nKN7XTok_89snJB9LPTmHKaKSoOgQVCT-cQB53c9fqhSM-o",
			Domain: ".gaokao.com",
			Path:   "/",
		},
	}

	jar.SetCookies(url, initCookie)

	downImg := NewDown(
		imgUrl,
		url.Host,
		"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
		jar,
		"./college_avatars/",
		strs[len(strs)-1])
	imgPath := downImg.DownImage()
	fmt.Println(imgPath)

}
